package com.samapp.indent;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.dragon.httpclient_util.HttpClientThread;
import com.dragon.httpclient_util.HttpResultHandle;
import com.dragon.httpclient_util.JsonUtils;
import com.samapp.MyApplication;
import com.samapp.R;
import com.samapp.entity.DetectionItem;
import com.samapp.entity.IndentDetail;
import com.samapp.entity.Samples;

public class AddIndentDetailsActivity extends Activity implements OnClickListener {

	/** 返回按钮 */
	private Button btnBack = null;
	/** 检测项目 */
	private Spinner spDetectionItem = null;
	/** 查询检测项目 */
	private ImageView imageSearchDetectionItem = null;
	/** 检测方法 */
	private EditText etDetectionMethod = null;
	/** 原价 */
	private EditText etOriginalPrice = null;
	/** 折扣 */
	private EditText etDiscount = null;
	/** 查询折扣 */
	private Button btnGetDiscount = null;
	/** 价钱 */
	private EditText etPrice = null;
	/** 样品 */
	private Spinner spSampleItem = null;
	/** 添加明细 */
	private Button btnAddDetail = null;
	/** 检测项目Id */
	private String testItemId;
	/** 检测项目名称 */
	private String testItemName;
	/** 检测方法Id */
	private String testMethodId;
	/** 检测低限 */
	private String basePrice;
	/** 折扣 */
	private String discountRate;
	/** 价钱 */
	private String actualPrice;
	/** 样品序号 */
	private String sampleSn;
	private String message;
	/** 被选中的检测项目 */
	private DetectionItem mDetectionItem;
	/** 被选中的样品 */
	private Samples mSampleItem;

	private MyApplication myApplication = MyApplication.getApplicationInstance();
	/** 检测项目 */
	public static final int CODE_DETECTION_ITEM = 0x190;
	/** 检测方法 */
	public static final int MSG_DETECTION_METHOD = 0x191;
	/** 获取折扣权限 */
	public static final int MSG_DISCOUNT = 0x192;
	/** 异常提示 */
	public static final int MSG = 0x193;
	// private final String[] text = { " " };
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == MSG_DETECTION_METHOD) {
				etDetectionMethod.setText(testMethodId);
				etOriginalPrice.setText(basePrice);
			} else if (msg.what == MSG_DISCOUNT) {
				etDiscount.setText(discountRate);
				if (!(etOriginalPrice.getText().toString().equals(""))) {
					etPrice.setText(Double.parseDouble(etOriginalPrice.getText().toString()) * Double.parseDouble(etDiscount.getText().toString()) + "");
				}
			} else if (msg.what == MSG) {
				Toast.makeText(AddIndentDetailsActivity.this, message, Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_indent_details);
		init();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	private void init() {
		myApplication.listDetectionItem.clear();
		initView();
		initListener();
		initData();
	}

	private void initView() {
		btnBack = (Button) findViewById(R.id.btn_back);
		spDetectionItem = (Spinner) findViewById(R.id.sp_detectionItem);
		spDetectionItem.setEnabled(false);
		imageSearchDetectionItem = (ImageView) findViewById(R.id.image_search_detectionItem);
		etDetectionMethod = (EditText) findViewById(R.id.detectionMethod);
		etOriginalPrice = (EditText) findViewById(R.id.base_price);
		etDiscount = (EditText) findViewById(R.id.discount);
		btnGetDiscount = (Button) findViewById(R.id.btn_search_discount);
		etPrice = (EditText) findViewById(R.id.price);
		spSampleItem = (Spinner) findViewById(R.id.sp_sample);
		btnAddDetail = (Button) findViewById(R.id.btn_add_detail);
	}

	private void initListener() {
		btnBack.setOnClickListener(this);
		imageSearchDetectionItem.setOnClickListener(this);
		btnGetDiscount.setOnClickListener(this);
		btnAddDetail.setOnClickListener(this);
	}

	private void initData() {
		initSampleSpinner();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.image_search_detectionItem:
			Intent detectionItemIntent = new Intent(this, DetectionItemActivity.class);
			detectionItemIntent.putExtra("intentMark", "AddIndentDetailsActivity");
			startActivityForResult(detectionItemIntent, CODE_DETECTION_ITEM);
			break;
		case R.id.btn_search_discount:
			getDiscount();
			break;
		case R.id.btn_add_detail:
			if (mDetectionItem == null) {
				Toast.makeText(AddIndentDetailsActivity.this, "请选择检测项目", Toast.LENGTH_SHORT).show();
				break;
			} else {
				setData();
				finish();
				break;
			}
		}
	}

	private void setData() {
		testItemId = mDetectionItem.getId();
		testItemName = mDetectionItem.getCnname();
		testMethodId = etDetectionMethod.getText().toString();
		basePrice = etOriginalPrice.getText().toString();
		discountRate = etDiscount.getText().toString();
		actualPrice = etPrice.getText().toString();
		sampleSn = mSampleItem.getSn();
		myApplication.newIndent.getOrderDetail().add(new IndentDetail(sampleSn, testItemId, testItemName, testMethodId, basePrice, discountRate, actualPrice));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		switch (resultCode) {
		case CODE_DETECTION_ITEM:
			spDetectionItem.setEnabled(true);
			initSpinner();
			break;
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	private void initSpinner() {
		String[] mDetections = new String[myApplication.listDetectionItem.size()];
		for (int i = 0; i < mDetections.length; i++) {
			mDetections[i] = myApplication.listDetectionItem.get(i).getCnname();
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mDetections);
		adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		spDetectionItem.setAdapter(adapter);
		spDetectionItem.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				mDetectionItem = myApplication.listDetectionItem.get(position);
				detectionMethod();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
	}

	private void initSampleSpinner() {
		String[] mSamples = new String[myApplication.newIndent.getSamples().size()];
		for (int i = 0; i < mSamples.length; i++) {
			mSamples[i] = myApplication.newIndent.getSamples().get(i).getCname();
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mSamples);
		adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		spSampleItem.setAdapter(adapter);
		spSampleItem.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				mSampleItem = myApplication.newIndent.getSamples().get(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
	}

	/**
	 * 根据检测项目查询检测方法和原价
	 */
	private void detectionMethod() {
		String url = myApplication.url + "queryTestMethod.htm";
		Map<String, String> myMap = new HashMap<String, String>();
		myMap.put("accessToken", "5C9.yx0S");
		myMap.put("FId", mDetectionItem.getId());
		HttpClientThread.getmHttpClientThread().post(url, myMap, new HttpResultHandle() {

			@Override
			public void onSuccess(String response) {
				Log.i("Long", response);
				String code = JsonUtils.getValue(response, "code");
				if ("0".equals(code)) {
					testMethodId = JsonUtils.getValue(response, "id");
					basePrice = JsonUtils.getValue(response, "price");
					mHandler.sendEmptyMessage(MSG_DETECTION_METHOD);
				} else {
					message = JsonUtils.getValue(response, "msg");
					mHandler.sendEmptyMessage(MSG);
				}
			}

			@Override
			public void onFailure(int statusCode) {
				message = "连接服务器失败，状态码：" + statusCode;
				mHandler.sendEmptyMessage(MSG);
			}
		});
	}

	/**
	 * 根据用户ID获取折扣权限
	 */
	private void getDiscount() {
		String url = myApplication.url + "getDiscount.htm";
		Map<String, String> myMap = new HashMap<String, String>();
		myMap.put("accessToken", "5C9.yx0S");
		myMap.put("FId", myApplication.currentUser.getUserName());
		HttpClientThread.getmHttpClientThread().post(url, myMap, new HttpResultHandle() {

			@Override
			public void onSuccess(String response) {
				Log.i("Long", response);
				String code = JsonUtils.getValue(response, "code");
				if ("0".equals(code)) {
					discountRate = JsonUtils.getValue(response, "discount");
					mHandler.sendEmptyMessage(MSG_DISCOUNT);
				} else {
					message = JsonUtils.getValue(response, "msg");
					mHandler.sendEmptyMessage(MSG);
				}
			}

			@Override
			public void onFailure(int statusCode) {
				message = "连接服务器失败，状态码：" + statusCode;
				mHandler.sendEmptyMessage(MSG);
			}
		});
	}
}
